package com.xinzhidi.web.equipmentAlarm.service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.xinzhidi.common.core.domain.model.LoginUser;
import com.xinzhidi.common.core.page.TableDataInfo;
import com.xinzhidi.common.utils.DateUtils;
import com.xinzhidi.common.utils.SecurityUtils;
import com.xinzhidi.common.utils.bean.BeanUtils;
import com.xinzhidi.framework.websocket.WebSocketUsers;
import com.xinzhidi.web.equipmentAlarm.domain.EquipmentAlarm;
import com.xinzhidi.web.equipmentAlarm.domain.dto.EquipmentAlarmAddDto;
import com.xinzhidi.web.equipmentAlarm.domain.dto.EquipmentAlarmDto;
import com.xinzhidi.web.equipmentAlarm.domain.dto.EquipmentAlarmListDto;
import com.xinzhidi.web.equipmentAlarm.domain.dto.EquipmentAlarmUpdDto;
import com.xinzhidi.web.equipmentAlarm.domain.vo.EquipmentAlarmInfoVo;
import com.xinzhidi.web.equipmentAlarm.domain.vo.EquipmentAlarmListVo;
import com.xinzhidi.web.equipmentAlarm.mapper.EquipmentAlarmMapper;
import com.xinzhidi.web.netty.utils.SecurityAdminUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;


/**
 * 设备告警Service业务层处理
 *
 * @author ruoyi
 * @date 2023-05-31
 */
@Service
public class EquipmentAlarmService extends ServiceImpl<EquipmentAlarmMapper, EquipmentAlarm> {
    @Autowired
    private EquipmentAlarmMapper equipmentAlarmMapper;

    /**
     * 查询设备告警
     *
     * @param id 设备告警主键
     * @return 设备告警
     */
    public EquipmentAlarmInfoVo selectEquipmentAlarmById(Long id) {
        EquipmentAlarm equipmentAlarm = equipmentAlarmMapper.selectById(id);
        EquipmentAlarmInfoVo infoVo = new EquipmentAlarmInfoVo();
        BeanUtils.copyProperties(equipmentAlarm, infoVo);
        return infoVo;
    }

    /**
     * 查询设备告警列表
     *
     * @param dto 查询设备告警dto
     * @return 设备告警
     */
    public TableDataInfo<EquipmentAlarmListVo> selectEquipmentAlarmList(EquipmentAlarmListDto dto) {
        List<Long> userPlotIds = SecurityAdminUtils.getUserPlotIds();
        this.getKeywordList(dto);
        List<EquipmentAlarmListVo> list = this.baseMapper.selectEquipmentAlarmListVo(dto, userPlotIds);
        return TableDataInfo.getDataTable(list);
    }

    public void getKeywordList(EquipmentAlarmListDto dto) {
        String keyword = dto.getKeyword();
        if (StringUtils.isBlank(keyword)) {
            return;
        }
        if("通讯异常".equals(keyword)){
            keyword = "通讯异常";
        }else if("回温异常".equals(keyword)){
            keyword = "】回水温度";
        }else if ("供温异常".equals(keyword)) {
            keyword = "供水温度";
        }else if ("室温异常".equals(keyword)) {
            keyword = "室内温度";
        }else if ("流量异常".equals(keyword)) {
            keyword = "流量";
        }
        else if ("开度异常".equals(keyword)) {
            keyword = "开度";
        }
        dto.setKeyword(keyword);

    }

    /**
     * 新增设备告警
     *
     * @param dto 新增设备告警dto
     * @return 结果
     */
    public int insertEquipmentAlarm(EquipmentAlarmAddDto dto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        EquipmentAlarm equipmentAlarm = new EquipmentAlarm();
        BeanUtils.copyProperties(dto, equipmentAlarm);
        equipmentAlarm.setCreateBy(loginUser.getUserId().toString());
        equipmentAlarm.setCreateTime(DateUtils.getNowDate());
        return equipmentAlarmMapper.insert(equipmentAlarm);
    }

    /**
     * 修改设备告警
     *
     * @param dto 修改设备告警dto
     * @return 结果
     */
    public int updateEquipmentAlarm(EquipmentAlarmUpdDto dto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        EquipmentAlarm equipmentAlarm = new EquipmentAlarm();
        BeanUtils.copyProperties(dto, equipmentAlarm);
        equipmentAlarm.setUpdateBy(loginUser.getUserId().toString());
        equipmentAlarm.setStatus("1");
        equipmentAlarm.setUpdateTime(DateUtils.getNowDate());
        return equipmentAlarmMapper.updateById(equipmentAlarm);
    }

    /**
     * 批量删除设备告警
     *
     * @param ids 需要删除的设备告警主键
     * @return 结果
     */
    public int deleteEquipmentAlarmByIds(Long[] ids) {
        return equipmentAlarmMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备告警信息
     *
     * @param id 设备告警主键
     * @return 结果
     */
    public int deleteEquipmentAlarmById(Long id) {
        return equipmentAlarmMapper.deleteById(id);
    }

    /**
     * 获取需要发送的告警列表
     *
     * @return
     */
    public List<EquipmentAlarmListVo> getSendAlarmList(EquipmentAlarmListDto dto) {
        List<Long> userPlotIds = SecurityAdminUtils.getUserPlotIds();
        List<EquipmentAlarmListVo> list = baseMapper.getSendAlarmList(userPlotIds, dto);
        return list;
    }

    /**
     * 获取需要发送的告警列表
     *
     * @return
     */
    public void messagePush() {
        System.out.println("检查是否有可推送的消息");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return;
        }
        Long userId = loginUser.getUser().getUserId();
        //查询需要消息提醒的告警
        EquipmentAlarmListDto dto = new EquipmentAlarmListDto();
        dto.setHideOrPush(0);
        dto.setStatus("0");
        List<EquipmentAlarmListVo> equipmentAlarms = this.getSendAlarmList(dto);
        if (CollectionUtils.isEmpty(equipmentAlarms)) {
            return;
        }

        //找出需要发送的数据
        //1:找出未发送信息的数据（需要立即发送）
        List<EquipmentAlarmListVo> noSendList = Lists.newArrayList();
        for (EquipmentAlarmListVo vo : equipmentAlarms) {
            if (vo.getLastSendTime() == null) {
                noSendList.add(vo);
                continue;
            }
            LocalDateTime lastSendTime = vo.getLastSendTime();
            long minutes = Duration.between(LocalDateTime.now(), lastSendTime).toMinutes();
            //如果相差的分钟数是设置间隔数的整数，则需要推送
            if (minutes % vo.getPushInterval() == 0) {
                noSendList.add(vo);
            }
        }

        if (noSendList.size() > 0) {
            UpdateWrapper<EquipmentAlarm> updateWrapper = new UpdateWrapper<>();
            JSONObject jsonObject;
            for (EquipmentAlarmListVo vo : noSendList) {
                updateWrapper = new UpdateWrapper<>();
                jsonObject = new JSONObject();
                jsonObject.put("type", 1);
                jsonObject.put("message", "设备【" + vo.getEquipmentName() + "】" + vo.getAlarmTypeName());
                WebSocketUsers.sendMessageToUserByUserId(userId + "", jsonObject.toString());
            }
            updateWrapper.set("last_send_time", LocalDateTime.now()).in("id", noSendList.stream().map(EquipmentAlarmListVo::getId).toArray());
            this.update(updateWrapper);
        }
    }

    public EquipmentAlarm getByParam(EquipmentAlarmDto dto) {
        QueryWrapper<EquipmentAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(dto.getEquipmentId() != null, "equipment_id", dto.getEquipmentId());
        queryWrapper.eq(dto.getAlarmSettingId() != null, "alarm_setting_id", dto.getAlarmSettingId());
        queryWrapper.eq(dto.getStatus() != null, "status", 0);

        queryWrapper.like(dto.getRemark() != null, "remark", dto.getRemark());
        return this.getOne(queryWrapper);

    }


}
